package com.llb666.shop.items.domain.service;

import com.llb666.common.core.exception.AppException;
import com.llb666.common.core.web.error.CommonError;
import com.llb666.common.core.web.error.ErrorCode;
import com.llb666.shop.items.api.vo.NewItemsVo;
import com.llb666.shop.items.domain.entity.Category;
import com.llb666.shop.items.domain.repository.CategoryRepository;
import com.mysql.cj.xdevapi.Collection;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * 商品类目service.
 *
 * @author llb666
 * @version 1.0.0
 */
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class CategoryService {

    private final CategoryRepository categoryRepository;

    /**
     * 查询一级商品类目.
     *
     * @return 一级商品类目列表
     */
    public List<Category> queryAllCategoryRoot() {
        return categoryRepository.queryAllCategoryRoot();
    }

    /**
     * 根据父级商品类目id,查询子级商品类目列表.
     *
     * @param rootCatId 父级商品类目Id.
     * @return 商品类目列表
     */
    public List<Category> getCategoryByRootCatId(Integer rootCatId) {
        return categoryRepository.getCategoryByRootCatId(rootCatId);
    }

    /**
     * 根据父级商品类目id列表,查询子级商品类目列表.
     *
     * @param rootCatIds 父级商品类目Id列表.
     * @return 商品类目列表
     */
    public List<Category> getCategoryByRootCatIds(Set<Integer> rootCatIds) {
        return categoryRepository.getCategoryByRootCatIds(rootCatIds);
    }

    /**
     * 根据商品类目id查询类目列表.( 实际只有一个商品类目，前端页面映射使用的列表)
     *
     * @param rootCatIds 一级商品类目Id，一级商品类目下的商品推荐
     * @return 商品类目列表
     */
    public List<Category> getCategoryByRootId(Integer rootCatIds) {
        List<Category> categories = categoryRepository.getCategoryByRootId(Collections.singletonList(rootCatIds));
        Optional<Category> errorTypeCat = categories.stream().filter(e -> !e.getType().equals(1)).findAny();
        if (errorTypeCat.isPresent()) {
            throw new AppException(CommonError.RequestParamsInvalid, "传入的参数rootCatId非一级商品分类！");
        }
        return categories;
    }
}
